package fast;

import java.io.IOException;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * UDPListener Class
 * 
 * Provides a UDP socket listening on a port, any connections made to this port
 * will have their data written to a buffer. Must be run as a thread.
 * 
 * @version 0.1
 * @author Adam Bell
 * @date 17/01/2010
 */
public class UDPListener implements Runnable {
	private int port;
	private Buffer listenBuffer;
	private DatagramSocket s;

	/**
	 * Constructor
	 * 
	 * @param port
	 *            The port to listen on
	 * @param listenBuffer
	 *            The buffer to add entries to
	 */
	public UDPListener(int p, Buffer b) {
		port = p;
		listenBuffer = b;
	}

	/**
	 * Thread actions
	 */
	public void run() {

		try {
			s = new DatagramSocket(port);
		} catch (SocketException e) {
			e.printStackTrace();
		}

		while (true) {

			// TODO:Better buffer sizing
			byte[] b = new byte[50];
			DatagramPacket r = new DatagramPacket(b, b.length);

			try {
				s.receive(r);

				byte[] d = r.getData();
				String data = "";

				for (int i = 0; i < d.length; i++) {
					data = data + (char) d[i];
				}

				// remove a pre-pended "/" from the address
				// remove trash characters
				listenBuffer.add(r.getAddress().toString().substring(1) + "|"
						+ data.trim());

			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}

	}
}
